<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '商品详情',
  },
}
</route>

<script lang="ts" setup>
import { ref, defineAsyncComponent, onMounted } from 'vue'
import { useToast } from 'wot-design-uni'
import { getGoodsDetail } from '@/service/goods/index'
import type { GoodsInfoVo, GoodsSku } from '@/service/goods/goods.d'
import { checkCollectStatus, addCollect, deleteCollect } from '@/service/goods/collect/collect'
import { getCommentTags } from '@/service/goods/comment/comment'
import { GoodsBrowseHistoryApi } from '@/service/goods/history/history'
import { useActiveCartStore } from '@/store/activeCart'

const ProductSku = defineAsyncComponent(() => import('@/components/product/prodct-sku.vue'))
const SelectdProduct = defineAsyncComponent(() => import('@/components/selectdProduct/index.vue'))

const activeCartStore = useActiveCartStore()
const toast = useToast()
const SelectdProductRef = ref()

const isFooterBar = ref(true)
const activeSkuId = ref<number>(null)
const activeSKu = ref<GoodsSku>()
const activeGid = ref()
// 商品数据
const goodsData = ref<GoodsInfoVo>({} as GoodsInfoVo)

const commentData = reactive({
  total: 0,
  averageScore: 4.5,
  tags: [] as Array<{ id: number; tagName: string; useCount: number }>,
})
const brandList = ref([])
onLoad(async (options) => {
  // 接收 URL 参数
  console.log('商品ID:', options.id)
  activeSkuId.value = options.skuId
  activeGid.value = options.id

  try {
    const { code, data } = await getGoodsDetail(options.id)
    checkedCollect(activeSkuId.value)
    GoodsBrowseHistoryApi.add(activeSkuId.value)
    console.log(data)
    if (code === 200 && data) {
      goodsData.value = data
      brandList.value = [
        { title: '品牌', detail: goodsData.value.brandName },
        { title: '净含量', detail: goodsData.value.netContent },
        { title: '酒精度', detail: goodsData.value.alcoholContent },
        { title: '产地', detail: goodsData.value.origin },
      ]
      data.goodsSkuList.forEach((sku) => {
        if (sku.id === activeSkuId.value) {
          activeSKu.value = sku
        }
      })
    }
  } catch (error) {
    console.log(error)
    uni.showToast({})
  }
})

const handlerPop = () => {
  isFooterBar.value = true
}
const handleSkuSelect = (skuId: number) => {
  activeSkuId.value = skuId
  goodsData.value.goodsSkuList.forEach((element) => {
    if (activeSkuId.value === element.id) {
      activeSKu.value = element
    }
  })
  checkedCollect(skuId)
}

const checkedCollect = async (skuId) => {
  const { code, data } = await checkCollectStatus(skuId)
  if (code === 200 && data) {
    isCollected.value = data
  }
}
// 收藏状态
const isCollected = ref(false)
const changeCollerct = async () => {
  const apiMethod = isCollected.value ? deleteCollect : addCollect
  const { code, data } = await apiMethod(activeSkuId.value)
  if (code === 200 && data) {
    isCollected.value = data
  } else {
    toast.show('操作失败')
  }
}

const handleNavigateCart = () => {
  console.log((activeSKu.value.id, activeSKu.value.goodsId))

  SelectdProductRef.value.hanleOpen(activeSKu.value.id, activeSKu.value.goodsId)
  isFooterBar.value = false
}

const handleCustomerService = () => {}

const goGoodsCommentList = () => {
  uni.navigateTo({ url: `/pages/goods/comment/index?goodsId=${activeGid.value}` })
}

const activeTag = ref<number>(0)

// 获取评论数据
onMounted(async () => {
  try {
    const { code, data } = await getCommentTags(activeGid.value)
    if (code === 200 && data) {
      console.log(data)

      commentData.averageScore = data.score
      commentData.tags = data.tags
      commentData.total = data.count
    }
  } catch (error) {
    console.error('获取评论失败', error)
  }
})

// 标签点击处理
const handleTagClick = (tagId: number) => {
  activeTag.value = tagId
  // 这里可以添加筛选逻辑
}

const goComentInfo = () => {
  uni.navigateTo({ url: `/pages/goods/comment/index?goodsId=${goodsData.value.id}` })
}
</script>
<template>
  <view class="goods-detail-container">
    <!-- 商品主图轮播 -->
    <swiper class="swiper-box" autoplay circular indicator-dots>
      <swiper-item v-for="(item, index) in goodsData.sliderUrls?.split(',')" :key="index">
        <!-- <image :src="item" mode="aspectFill" class="swiper-image" /> -->
        <image-container :src="item" max-width="100%" />
      </swiper-item>
    </swiper>

    <!-- 商品基础信息 -->
    <view class="goods-base-info">
      <view class="price-section">
        <view>
          <text class="current-price">
            <text style="font-size: 24rpx">¥</text>
            {{ activeSKu?.salePrice }}
          </text>
          <text class="original-price">¥{{ activeSKu.marketPrice }}</text>
          <text class="discount-tag">
            {{ (activeSKu?.salePrice / activeSKu.marketPrice).toFixed(1) }}折
          </text>
        </view>
        <view>
          <view
            v-if="!isCollected"
            @click="changeCollerct"
            class="tabbar-a-hongxin iconfont"
            style="font-size: 48rpx"
          ></view>
          <view
            v-else
            @click="changeCollerct"
            class="tabbar-aixin iconfont"
            style="font-size: 48rpx; color: red !important"
          ></view>
        </view>
      </view>
      <text class="goods-title">{{ activeSKu.skuName }}</text>
      <view class="goods-introduction">{{ goodsData.introduction }}</view>

      <scroll-view scroll-x>
        <view class="specs-list">
          <ProductSku
            v-for="item in goodsData.goodsSkuList"
            :key="item.id"
            :skuItem="item"
            :netContent="goodsData.netContent"
            :selected="activeSkuId == item.id"
            @click="handleSkuSelect(item.id)"
          />
        </view>
      </scroll-view>
    </view>
    <!-- 新增品牌信息通栏 -->
    <view class="brand-info-section">
      <scroll-view scroll-x class="brand-scroll" :show-scrollbar="false">
        <view class="brand-list">
          <view
            v-for="(item, index) in brandList"
            :key="index"
            class="brand-item"
            :class="{ last: index === brandList.length - 1 }"
          >
            <text class="brand-title">{{ item.title }}</text>
            <text class="brand-detail">{{ item.detail }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- 用户评价 -->
    <view class="comment-section" v-if="Number(commentData.total) > 0">
      <!-- 评论模块容器 -->
      <view class="comment-container">
        <!-- 评论头部 -->
        <view class="comment-header">
          <text class="header-title">评价</text>
          <view class="comment-header-right">
            <view class="comment-count" @click.stop="goComentInfo">
              {{ commentData.total }}条评论
            </view>
            <view class="icon-youjiantou iconfont" style="font-size: 20rpx; color: #999"></view>
          </view>
        </view>

        <!-- 标签与评分 -->
        <view class="comment-body">
          <scroll-view scroll-x class="tag-scroll" :show-scrollbar="false">
            <view
              v-for="(tag, index) in commentData.tags"
              :key="index"
              class="comment-tag"
              :class="{ active: activeTag === tag.id }"
              @click="handleTagClick(tag.id)"
            >
              {{ tag.tagName }}（{{ tag.useCount }}）
            </view>
          </scroll-view>
          <view class="rating-section" @click="goGoodsCommentList">
            <text class="average-score">{{ commentData.averageScore.toFixed(1) }}</text>
            <wd-rate v-model="commentData.averageScore" readonly size="8" space="0px" />
          </view>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="goods-detail-content">
      <!-- <rich-text :nodes="goodsData.details" /> -->
      <mp-html
        :content="goodsData.details"
        :tag-style="{
          img: 'display:block;margin:0',
          div: 'margin:0!important',
        }"
      />
    </view>

    <!-- 底部操作栏 -->
    <view class="footer-bar safe-area" v-show="isFooterBar">
      <!-- <view class="footer-icon">
        <view class="flex flex-col justify-center text-center footer-icon-item footer-icon-kefu">
          <view class="iconfont tabbar-kefu" style="font-size: 44rpx; color: aliceblue"></view>
          <text style="font-size: 24rpx">客服</text>
        </view>

        <view class="flex flex-col justify-center text-center footer-icon-item">
          <view
            class="iconfont tabbar-gouwuche cart-icon-box"
            style="font-size: 44rpx; color: aliceblue"
          >
            <view class="cart-count">{{ activeCartStore.selectedCount }}</view>
          </view>

          <text style="font-size: 24rpx">购物车</text>
        </view>
      </view> -->

      <view class="fution-item add-cart" @click="handleNavigateCart"><view>加入购物车</view></view>
      <view class="fution-item now-buy" @click="handleNavigateCart"><view>立即购买</view></view>
    </view>
    <SelectdProduct ref="SelectdProductRef" @pop-close="handlerPop" />
  </view>
</template>
<style lang="scss" scoped>
.goods-detail-container {
  padding-bottom: 100px;
  background-color: #f5f5f5;
  .swiper-box {
    height: 700rpx;
    margin-bottom: 20rpx;
    .swiper-image {
      width: 100%;
      height: 100%;
    }
  }

  .goods-base-info {
    padding: 20rpx 20rpx;
    margin: 0 16rpx;
    background: white;
    border-radius: 16rpx;
    .price-section {
      display: flex;
      align-items: baseline;
      justify-content: space-between;
      margin-bottom: 15rpx;

      .current-price {
        margin-right: 20rpx;
        font-size: 36rpx;
        font-weight: bold;
        color: #e93b3b;
      }

      .original-price {
        margin-right: 20rpx;
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }

      .discount-tag {
        padding: 5rpx 15rpx;
        font-size: 24rpx;
        color: #e93b3b;
        background: linear-gradient(90deg, #ffe8e8, #ffd0d0);
        border-radius: 8rpx;
      }
    }

    .goods-title {
      margin-bottom: 20rpx;
      font-size: 32rpx;
      font-weight: bold;
      line-height: 1.4;
      color: #000;
    }
    .goods-introduction {
      margin-top: 10rpx;
      font-size: 24rpx;
      line-height: 1.4;
      color: #999;
    }
    .specs-list {
      display: flex;
      justify-content: flex-start;
      margin-top: 20rpx;

      .spec-item {
        padding: 15rpx 40rpx;
        font-size: 28rpx;
        color: #666;
        background: #f5f5f5;
        border: none;
        border-radius: 50rpx;

        &.active {
          color: white;
          background: linear-gradient(90deg, #ff6969, #ff4040);
        }
      }
    }
  }

  .brand-info-section {
    padding: 20rpx;
    margin: 0 16rpx;
    margin-top: 16rpx;
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.02);

    .brand-scroll {
      width: 100%;
      height: 120rpx;
      white-space: nowrap;

      .brand-list {
        display: inline-flex;
        width: 100%;
        height: 100%;
        padding: 10rpx 0;
        background: #fbf5ec; // 浅橘色背景
        border-radius: 12rpx;
      }

      .brand-item {
        position: relative;
        display: flex;
        flex: 1;
        flex-direction: column;
        justify-content: center;
        min-width: 150rpx;
        text-align: center;

        // 虚线分割
        &:not(.last)::after {
          position: absolute;
          top: 50%;
          right: 0;
          height: 60%;
          content: '';
          border-right: 1rpx dashed #ffb082;
          transform: translateY(-50%);
        }

        .brand-title {
          margin-bottom: 8rpx;
          font-size: 20rpx;
          font-weight: 500;
          color: #333;
        }

        .brand-detail {
          font-size: 24rpx;
          color: #000;
        }
      }
    }
  }

  .section-title {
    display: block;
    padding: 30rpx;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    border-bottom: 1rpx solid #eee;
  }
  .goods-detail-content {
    margin: 16rpx;
    overflow: hidden;
    border-radius: 16rpx;
  }

  .comment-section {
    margin: 16rpx;
    background: white;
    border-radius: 16rpx;

    .comment-container {
      padding: 20rpx;

      .comment-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10rpx;

        .header-title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
        }
        .comment-header-right {
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .comment-count {
          font-size: 24rpx;
          color: #666;
        }
      }

      .comment-body {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10rpx;

        .tag-scroll {
          width: 200rpx;
          white-space: nowrap;
          .comment-tag {
            display: inline-block;
            padding: 8rpx 24rpx;
            margin-right: 20rpx;
            font-size: 24rpx;
            color: #666;
            background: #f5f5f5;
            border-radius: 40rpx;
            transition: all 0.3s;

            &.active {
              color: white;
              background: linear-gradient(90deg, #ff6969, #ff4040);
            }
          }
        }
        .rating-section {
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-left: 20rpx;
          .average-score {
            margin-right: 10rpx;
            font-size: 36rpx;
            color: #666;
          }
          &::after {
            position: absolute;
            top: 0;
            left: -10rpx;
            width: 1rpx;
            height: 100%;
            content: '';
            background-color: #eee;
          }
          &:deep {
            .wd-rate__item {
              width: 20rpx;
              height: 20rpx;
            }
          }
        }
      }
    }
  }

  .footer-bar {
    position: fixed;
    right: 0;
    bottom: 20rpx;
    left: 36rpx;
    z-index: 999;
    display: flex;
    align-items: center;
    max-width: 680rpx;
    height: 100rpx;
    overflow: hidden;
    background-color: #494949;
    // background-color: #fff;
    // border-top: 1rpx solid #f0f0f0;
    border-radius: 60rpx;
    // box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
    .footer-icon {
      display: flex;
      justify-content: flex-start;
      width: 280rpx;
      height: 100%;
      color: #fff;
      background: linear-gradient(-90deg, #383838, #181c1b);
      .footer-icon-item {
        width: 140rpx;

        .cart-icon-box {
          position: relative;
          .cart-count {
            position: absolute;
            top: -12rpx;
            right: 12rpx;
            z-index: 12;
            width: 30rpx;
            height: 30rpx;
            font-size: 24rpx;
            color: #fff;
            background-color: $uni-bg-themes;
            border: 6rpx solid #fff;
            border-radius: 50%;
          }
        }
      }
      .footer-icon-kefu {
        position: relative;
        &::after {
          position: absolute;
          top: 20rpx;
          right: 0;
          z-index: 9999;
          width: 4rpx;
          height: 60rpx;
          content: '';
          background-color: #494949;
        }
      }
    }
    .fution-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 400rpx;
      height: 100%;
      color: #fff;
    }
    .add-cart {
      background: linear-gradient(-90deg, #383838, #181c1b);
    }
    .now-buy {
      background-color: $uni-bg-themes;
    }
    .btn-group {
      display: flex;
      flex: 1;
      margin-left: 20rpx;

      .btn {
        flex: 1;
        height: 80rpx;
        font-size: 32rpx;
        font-weight: 500;
        border-radius: 50rpx;
        transition: all 0.2s;

        &::after {
          border: none;
        }
      }

      .cart-btn {
        color: #ff5c5c;
        background: linear-gradient(90deg, #fff3f3, #ffeaea);

        &:active {
          opacity: 0.9;
        }
      }

      .buy-btn {
        color: white;
        background: linear-gradient(90deg, #ff6969, #ff4040);

        &:active {
          opacity: 0.9;
        }
      }
    }
  }

  // 适配全面屏底部安全区域
  .safe-area {
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }
}
</style>
